import './com.js'
import { getDB} from "./indexedDB.js"
// const db = new IndexedDBWrapper("MyDatabase", 1, "books");
//方法1. alt w 和alt q是通过后台脚本触发按钮事件给前端脚本内容发送消息
//方法2. ←和→是 内容脚本给后台脚本发送事件,获取数据后给前端回调方法显示内容

let currentRead=undefined
const db = getDB("MyDatabase", 2, [
  { name: "books", options: { keyPath: "id" }, indexes: [{ name: "chapters", keyPath: "chapters" }] },
  { name: "bookOnLineSetting", options: { keyPath: "id" } }
])
/**
 * 方法1
 */
chrome.commands.onCommand.addListener((command) => {
  if (command === "move-left") {
    // 向 popup 发送消息
    turnPage(-1)
  } else if (command === "move-right") {
    // 向 popup 发送消息
    turnPage(1)
  }
});


/**
 * 方法2   监控内容组件给后台脚本的信息
 */
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.action === "fetchData") {
    const { addPage } = message;
    (async () => {
      const result = await turnPage(message.addPage, false);
      sendResponse({ status: "success", data: result });
    })();
    return true; 
  }
  return true; // 支持异步响应
});

const turnPage = async (addNumber,isSender=true) => {
  const allBooks =await db.getAll("books")
  if (allBooks.length < 1) {
    console.log('未找到数据', allBooks)
    return 111
  }
  const book = allBooks[0]
  currentRead=currentRead?currentRead+addNumber:book.read+addNumber
  book.read=currentRead
  const content = book.chapters[currentRead]
  if (!content) {
    console.log("获取章节失败 --turnPage");
    return addNumber
  }

  await saveChapter(book, db)
  if(isSender){
    const tabs = await chrome.tabs.query({ url: "*://*/*" });
    tabs.forEach(tab => {
      chrome.tabs.sendMessage(tab.id, {
        action: "triggerFunction",
        data:content
      });
    });
  }
  console.log('跳转页面返回数据content',content)
  return content
}



/**
 * 保存章节
 * @param {*} newChapter 
 */
const saveChapter = async (book, db) => {

  await db.update("books",{ id: book.id, chapters: book.chapters, read: book.read });

}
